package com.hotel.common.user.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hotel.common.config.RabbitKeyConfig;
import com.hotel.common.param.GrowthAdd;
import com.hotel.common.param.MqMsg;
import com.hotel.common.user.entity.MoneyLog;
import com.hotel.common.user.entity.Wallet;
import com.hotel.common.user.mapper.MoneyLogMapper;
import com.hotel.common.user.mapper.WalletMapper;
import com.hotel.common.user.service.WalletService;
import com.hotel.user.entity.User;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 用户余额表 服务实现类
 * </p>
 *
 * @author KK
 * @since 2024-06-15
 */
@Service
public class WalletServiceImpl extends ServiceImpl<WalletMapper, Wallet> implements WalletService {

    @Autowired
    private WalletMapper walletMapper;

    @Autowired
    private MoneyLogMapper moneyLogMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public boolean updateMoney(Integer userId, Integer money) {
        //1.查询用户余额
        QueryWrapper<Wallet> walletQueryWrapper = new QueryWrapper<>();
        walletQueryWrapper.eq("user_id", userId);
        Wallet wallet = walletMapper.selectOne(walletQueryWrapper);
        if (wallet == null) {
            //2.如果用户余额为空，则创建一个
            Wallet wallet1 = new Wallet();
            wallet1.setUserId(userId);
            wallet1.setMoney(money);
            wallet1.setTotalMoney(money);
            return this.save(wallet1);
        } else {
            //3.如果用户余额不为空，则更新余额
            wallet.setMoney(wallet.getMoney() - money * 100);
            int i = walletMapper.updateById(wallet);
            if (i <= 0){
                return false;
            }

        }
        //4.记录余额变动日志
        MoneyLog moneyLog = new MoneyLog();
        moneyLog.setUserId(userId);
        moneyLog.setMoney(money * 100);
        moneyLog.setType(2);//减少余额
        moneyLog.setFlag("购买会员");
        moneyLog.setInfo("会员消费");
        moneyLog.setCtime(new Date());

        // 5.积分增加 发送消息
        MqMsg mqMsg = new MqMsg();
        mqMsg.setId(IdUtil.getSnowflakeNextId());//雪花算法，用来生成唯一的id
        mqMsg.setType(5);

        GrowthAdd growthAdd = new GrowthAdd();
        growthAdd.setUid(userId);
        growthAdd.setType("会员加分");
        growthAdd.setGrowth(money);

        mqMsg.setMsg(growthAdd);

        rabbitTemplate.convertAndSend("", RabbitKeyConfig.Q_USER_GROWTH,mqMsg);

        moneyLogMapper.insert(moneyLog);
        return true;
    }
}
